# -*- coding: utf-8 -*-
import cgi
import os
import time
import datetime

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class Landmark(db.Model):
  #Classe com nome e localização de uma atração turística
  title = db.StringProperty()
  description =  db.StringProperty()
  lat = db.FloatProperty()
  lon = db.FloatProperty()
      
class LandmarkContent(db.Model):
  #Classe de um conteúdo de atração turística
  fk_landmark = db.StringProperty()
  type = db.IntegerProperty()
  language = db.StringProperty()
  url = db.StringProperty()

class LandmarkContentTags(db.Model):
  #Classe de um tag de um conteúdo de atração turística
  fk_landmark_content = db.StringProperty()
  tag = db.StringProperty()

class DroidGuideUserTags(db.Model):
  #Classe de pontos de uma tag na visão do usuário
  fk_user = db.StringProperty()
  tag = db.StringProperty()
  points = db.IntegerProperty()

class Location(db.Model):
  lat = db.FloatProperty()
  long = db.FloatProperty()
  speed = db.FloatProperty()
  datetime = db.DateTimeProperty(auto_now_add = True)

class Device(db.Model):
  name = db.StringProperty()
  location_key = db.StringProperty()
  batteryLevel = db.FloatProperty()
  connectivity = db.StringProperty()
  datetime = db.DateTimeProperty(auto_now = True)
  #db.StringProperty( 
  #choices=set(["", "WLAN", "GPRS", "BT", "disconnected"]))

class DroidGuideUser(db.Model):
  user = db.UserProperty()
  device_key = db.StringProperty()
  login_time = db.DateTimeProperty()
  logout_time = db.DateTimeProperty()
  datetime = db.DateTimeProperty(auto_now = True)
  state = db.StringProperty( 
        choices=set(["ACTIVE", "INACTIVE", "OUT-OF-SERVICE"]))
  
class Service(db.Model):
  description = db.StringProperty()
  type = db.StringProperty( 
        choices=set(["weather", "tourism", "traffic", "location", "business", "emergency", "shopping"]))
  state = db.StringProperty( 
        choices=set(["AVAILABLE", "IN-STATE", "OUT-OF-SERVICE", "EMERGENCY-ONLY", "COMSUMED"]))
  data = db.StringProperty()

class ServiceParameter(db.Model):
  type = db.StringProperty( 
        choices=set(["REQUEST", "RESPONSE"]))
  name = db.StringProperty()
  service_key = db.StringProperty()

class ServiceParameterValue(db.Model):
  service_parameter_key = db.StringProperty()
  service_key = db.StringProperty()
  droidGuideUser_key = db.StringProperty()
  value = db.StringProperty()
  validity_date = db.DateTimeProperty()

class ServiceEvent(db.Model):
  userToService_key = db.StringProperty()
  type = db.StringProperty( 
        choices=set(["ONE-TIME", "FOREVER"]))
  state = db.StringProperty( 
        choices=set(["AVAILABLE", "CONSUMED"]))
  data = db.StringProperty()
  datetime = db.DateTimeProperty(auto_now_add = True)

#User to Service Mapping
class UserToService(db.Model):
  droidGuideUser_key = db.StringProperty()
  service_key = db.StringProperty()
  datatime = db.DateTimeProperty(auto_now_add = True)

class DroidGuideEvent(db.Model):
  type = db.StringProperty( 
        choices=set(["location", "user", "device", "server", "service", "weather", "profile", "connectivity", "activity", "time"]))
  datetime = db.DateTimeProperty(auto_now_add = True)
  data = db.StringProperty()
  source = db.StringProperty( 
        choices=set(["user", "device", "server", "service", "location"]))	
  droidGuideUser_key = db.StringProperty()
  state = db.StringProperty( 
        choices=set(["AVAILABLE", "CONSUMED"]))

#DroidGuideActivity
class DroidGuideActivity(db.Model):
  landmark_id = db.StringProperty()
  signature = db.StringProperty();
#  consumer-historical-ecological-gastronomic-cultural-bohemian
  
class UserActivity(db.Model):
  droidGuideUser_key = db.StringProperty();
  activity_key = db.StringProperty();
  state = db.StringProperty( 
        choices=set(["created", "enqueued", "to be executed", "in execution", "executed", "canceled"]))	
  index = db.IntegerProperty()
  datetime = db.DateTimeProperty(auto_now = True)

class UserProfile(db.Model):
  name = db.StringProperty(default='Unknown', required=True)
  droidGuideUser_key = db.StringProperty()
  birth_year = db.IntegerProperty(default=0, required=True)
  gender = db.StringProperty(default='Unknown', required=True)
  marital_status = db.StringProperty(default='Unknown', required=True)
  food = db.BooleanProperty(default=False, required=True)
  drink = db.BooleanProperty(default=False, required=True)
  style = db.StringProperty(default='Unknown', required=True)
  consumer = db.IntegerProperty(default=0, required=True)
  historical = db.IntegerProperty(default=0, required=True)
  ecological = db.IntegerProperty(default=0, required=True)
  gastronomic = db.IntegerProperty(default=0, required=True)
  cultural = db.IntegerProperty(default=0, required=True)
  bohemian = db.IntegerProperty(default=0, required=True)
  weather = db.BooleanProperty(default=False, required=True)
  traffic = db.BooleanProperty(default=False, required=True)
  signature = db.StringProperty()
  datetime = db.DateTimeProperty(auto_now = True)

class UserContext(db.Model):
  droidGuideUser_key = db.StringProperty()
  hunger = db.IntegerProperty(default=0)
  mood = db.IntegerProperty(default=0)
  provision = db.IntegerProperty(default=0)
  sleep = db.IntegerProperty(default=0)
  time = db.IntegerProperty(default=0)
  datetime = db.DateTimeProperty(auto_now = True)

# constants
DROID_GUIDE_USER_KEY = 'droidGuideUser_key'
USER_TO_SERVICE_KEY = 'usertoservice_key'
MAX_RESULTS = 20
ACTIVITY_SIGNATURE_THRESHOLD = 2

# functions
def getObject(key):
    obj = db.get(db.Key(key))
    return obj

def listObjects(ObjName, self):
    results = ObjName.all()
    for result in results:
        self.response.out.write(result.to_xml())

def listObjectsFromQuery(q, self):
    for result in q:
        self.response.out.write(result.to_xml())

def deleteObject(key):
    obj = getObject(key)
    obj.delete()

def deleteObjectFromRequest(self):
    key = self.request.get('key')
    if key:
        deleteObject(key)

def deleteAll(ObjName):
    q = ObjName.all()
    db.delete(q)

def getProfileForUser(self):
#      print 'getProfileForUser'
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      name = self.request.get("name")
      q = None
      if droidGuideUser_key:
          q = UserProfile.gql("WHERE droidGuideUser_key = :dgkey",
               dgkey=droidGuideUser_key)
      elif name:
          q = UserProfile.gql("WHERE name = :1", name)

      if q:
#          print 'found profile'
          profile = q.get()
          if profile:
	          return profile

